#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/6/17 21:37
# @Author  : wuyupeng
# @FileName: bingo-upload.py
# @Software: PyCharm
import os
import sys
import click
import base64
import logging
from pathlib import Path
from repo_uploaders.repo_manager import RepoManagerFactory

OBS_AK = os.getenv("ak")
OBS_SK = os.getenv("sk")
OBS_ENDPOINT = os.getenv("obs_endpoint")
PYPI_TOKEN = os.getenv("PYPI_TOKEN")
PUBLIC_KEY = os.getenv("public_key")
PRIVATE_KEY = os.getenv("private_key")
APT_BUCKET = os.getenv("apt_bucket_name")
OBS_ROOT = os.getenv("obs_root")
GPG_PASSPHRASE = os.getenv("passphrase")
DEBUG_INFO = os.getenv("DEBUG") == "True"

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")


@click.command()
@click.option("--whl_path")
@click.option("--deb_path")
@click.option("--codename")
@click.option("--component")
@click.option("--arch")
@click.option("--use_test")
def main(whl_path, deb_path, codename, component, arch, use_test):
    params = [
        OBS_AK, OBS_SK, OBS_ENDPOINT, APT_BUCKET, 
        whl_path, deb_path, codename, component, arch, 
        PUBLIC_KEY, PRIVATE_KEY
    ]

    if not all(params):
        logging.info(f"Lack of params{params}, Please check.")
        sys.exit(-1)

    whl_full_path = Path(whl_path)
    deb_full_path = Path(deb_path)
    logging.info("whl: {}, deb: {}""".format(whl_full_path, deb_full_path))

    pypi_mgr = RepoManagerFactory.create(
        "pypi", whl_full_path, PYPI_TOKEN, use_test=(use_test == "True"), is_debug=DEBUG_INFO)
    apt_mgr = RepoManagerFactory.create(
        "obs", deb_full_path, codename, component, arch, OBS_ROOT, is_debug=DEBUG_INFO)

    pypi_pkg = pypi_mgr.prepare_package()
    pypi_mgr.upload_package(pypi_pkg)

    decoded_private_key = base64.b64decode(PRIVATE_KEY).decode()
    apt_mgr.init_apt_helper(OBS_AK, OBS_SK, OBS_ENDPOINT, APT_BUCKET)
    apt_pkg = apt_mgr.prepare_package(decoded_private_key, GPG_PASSPHRASE)
    apt_mgr.upload_package(apt_pkg, PUBLIC_KEY)


def test(deb_path, codename, comp, arch, obs_root, name, mail, passphrase, private_key=None):
    deb_full_path = Path(deb_path)
    logging.info("deb: {}""".format(deb_full_path))

    apt_mgr = RepoManagerFactory.create("obs", deb_full_path, codename, comp, arch, obs_root, is_debug=True)
    if not private_key:
        fp = apt_mgr.gpg_mgr.generate_key(name, mail, passphrase)
        private_key = apt_mgr.gpg_mgr.export_private_key(fp, passphrase)
    apt_pkg = apt_mgr.prepare_package(private_key, passphrase)
    logging.info(f"成功:{apt_pkg}")


if __name__ == '__main__':
    main()
